//
//  AccountLoginViewController.m
//  Finance
//
//  Created by Hu Jianguo on 13-4-15.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "AppDelegate.h"
#import "AccountLoginViewController.h"
//#import "ASIFormDataRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "AccountRegisterViewController.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
#import "AccountRegisterViewController.h"
#import "ResetLoginPasswordViewController.h"
@interface AccountLoginViewController ()

@end

@implementation AccountLoginViewController
@synthesize username,userpassword;
@synthesize autologin,lookbackpassword;
@synthesize btnlogin,btnRegister,btnNoautologin;
@synthesize registerUserName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
           self.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    AppDelegate* mydelegate = (AppDelegate* )[[UIApplication sharedApplication] delegate];
    if(mydelegate.loginName!= nil)
    {
        self.username.text = mydelegate.loginName;
    }
    else
    {
        self.username.text = @"请输入手机号/邮箱名/用户名";
        self.userpassword.text = @"请输入密码";
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.username.textColor = [UIColor grayColor];
    //self.username.text = @"请输入手机号/邮箱名/用户名";
    self.username.tag = 1;
    self.username.delegate = self;
    
    NSLog(@"username =%@",self.username.text);
    AppDelegate* mydelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];    
    if(mydelegate.loginName != nil)
    {
        self.username.text = mydelegate.loginName;
    }
    
    self.userpassword.textColor = [UIColor grayColor];
    //self.userpassword.text = @"请输入密码";
    self.userpassword.tag = 2;
    self.userpassword.delegate = self;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [self.navigationItem setLeftBarButtonItem:leftItem];
    
    
    self.username.text = registerUserName;
    
     UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    
    [self.view setBackgroundColor:bk];
    
    NSDictionary* mydic = [mydelegate readplist];
    if([[mydic objectForKey:@"islogin"] boolValue] == true)
    {
        self.btnNoautologin.hidden = true;
        self.autologin.hidden = false;
    }
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma - textdelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSInteger textID = textField.tag;
    if (textID == 1)
    {
        NSString* strUserName = self.username.text;
        if ([strUserName compare:@"请输入手机号/邮箱名/用户名"] == 0)
        {
            self.username.text = nil;
        }
    }

    if (textID == 2)
    {
         
        NSString* strPassword = self.userpassword.text;
        
        if ([strPassword compare:@"请输入密码"] == 0)
        {
            self.userpassword.text = nil;
        }
        
        [self.userpassword setSecureTextEntry:YES];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.userpassword setSecureTextEntry:YES];
    NSInteger textID = textField.tag;
    if (textID == 1)
    {
        NSString* strUserName = self.username.text;
        if ([strUserName compare:@""] == 0)
        {
            self.username.text = @"请输入手机号/邮箱名/用户名";
        }
        
        [self.username resignFirstResponder];
    }
    
    if (textID == 2)
    {
        NSString* strPassword = self.userpassword.text;
        
        if ([strPassword compare:@""] == 0)
        {
            self.userpassword.text = @"请输入密码";
        }
        
        [self.userpassword resignFirstResponder];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
 
    if([self.username isFirstResponder])
    {
        [self.userpassword becomeFirstResponder];
    }
    else if([self.userpassword isFirstResponder])
    {
        [self.userpassword resignFirstResponder];
    }

    return  YES;

}

#pragma - button event

-(IBAction)autoLogin :(id)sender
{
    self.btnNoautologin.hidden = true;
    self.autologin.hidden = false;
    
    NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]stringByAppendingPathComponent:@"Setting.plist"];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"username" ] = self.username.text;
    dic[@"password" ] = self.userpassword.text;
    dic[@"islogin" ] = @"1";
    
    [dic writeToFile:plistPath atomically:YES];
    
    AppDelegate* mydelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [mydelegate writeplist:@"username" PlistValue:self.username.text];
//    [mydelegate writeplist:@"password" PlistValue:self.userpassword.text];
//    [mydelegate writeplist:@"islogin" PlistValue:@"1"];
    
    NSDictionary* mydict = [mydelegate readplist];
    if(mydict)
    {
        NSLog(@"plist = %@",mydict);
    }
}

-(IBAction)noautoLogin :(id)sender
{
    self.btnNoautologin.hidden = false;
    self.autologin.hidden = true;
    AppDelegate* mydelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
    [mydelegate writeplist:@"username" PlistValue:self.username.text];
    [mydelegate writeplist:@"password" PlistValue:self.userpassword.text];
    [mydelegate writeplist:@"islogin" PlistValue:false];
}

-(IBAction)lookbackPassword:(id)sender
{
    [self setHidesBottomBarWhenPushed:YES];
    ResetLoginPasswordViewController* accountRegister = [[ResetLoginPasswordViewController alloc] initWithNibName:@"ResetLoginPasswordViewController" bundle:nil];
    
    [self.navigationController pushViewController:accountRegister animated:YES];
    
}

-(IBAction)userLogin:(id)sender
{
    //隐藏键盘
    [self.username resignFirstResponder];
    [self.userpassword resignFirstResponder];
    
    if (self.username.text == nil || self.userpassword.text == nil)
    {
        [self showMessageBox:@"提示" content:@"用户名或密码错误."];
        return;
    }
    
    NSString* strusername = [NSString stringWithFormat:@"%@",@"请输入手机号/邮箱名/用户名"];
    if(self.username.text == strusername)
    {
        [self showMessageBox:@"提示" content:@"用户名或密码错误."];
        return;
    }
    
    if ( [self.username.text compare:@""] == 0 ||
        [self.userpassword.text compare:@""] == 0)
    {
        [self showMessageBox:@"提示" content:@"用户名或密码不能为空."];
        return;
    }
   
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W106"];
    NSDictionary *body = [self setLoginPackketBody:self.username.text UserPassword:self.userpassword.text];
    
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    NSString *jsonString = [[NSString alloc] initWithData:requestJson encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",jsonString);
    
    //发送报文
    [self sendUserLoginInfo: requestJson];

}

-(NSDictionary*)setLoginPackketBody:(NSString*)userName  UserPassword:(NSString*)userPassword
{
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
    [dict setObject:userName forKey:@"userName"];
    [dict setObject:userPassword forKey:@"password"];
    
    return dict;
}

-(void)sendUserLoginInfo:(NSData*)jsonData
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"UserLogin"] toObject:self callBack:@selector(requestUserLoginCallBack:) withBody:jsonData];
}

-(void)requestUserLoginCallBack:(NSDictionary *)dic
{    
    NSDictionary* body = dic[@"body"];
    
    NSDictionary* header = dic[@"header"];
    if(body== nil && header != nil)
    {
        NSLog(@"test2%@",header[@"returnMessage"]);
                                               
        [self showMessageBox:@"登录提示" content:header[@"returnMessage"]];
        return;
    }

    if(body.count != 0)
    {
         AppDelegate* mydelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
        mydelegate.loginSessionID = body[@"sessionId"];
        mydelegate.loginName = self.username.text;
        
        [self.navigationController popViewControllerAnimated:YES];
        NSLog(@"sessionid %@",mydelegate.loginSessionID);
        [self backToMain];
    }

}

-(void)backToMain
{
    [self.view removeFromSuperview];
}

-(IBAction)userRegister:(id)sender
{
    [self setHidesBottomBarWhenPushed:YES];
    AccountRegisterViewController* accountRegister = [[AccountRegisterViewController alloc] initWithNibName:@"AccountRegisterViewController" bundle:nil];
    
    [self.navigationController pushViewController:accountRegister animated:YES];
}



#pragma -
-(void)showMessageBox:(NSString*)title content:(NSString*)content
{
    UIAlertView* msg = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [msg show];
}

@end
